<template>
  <div class="app-container">
    <!-- 查询模块 -->
    <div class="formDiv">
      <el-form ref="form" :inline="true" :model="form" label-width="140px">
        <el-row>
          <el-col :span="6">
            <el-form-item label="回款单号">
              <el-input v-model="form.repaymentSn"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="流水单号">
              <el-input v-model="form.orderSn"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="回款状态">
              <el-select v-model="form.status" clearable placeholder="请选择">
                <el-option
                  v-for="item in backStatus"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="姓名">
              <el-input v-model="form.userName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="手机号">
              <el-input v-model="form.userPhone"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="是否逾期">
              <el-select v-model="form.isExceed" clearable placeholder="请选择">
                <el-option
                  v-for="item in StatusOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="报单类型">
              <el-select v-model="form.formType" clearable placeholder="请选择">
                <el-option label="全部" :value="null"></el-option>
                <el-option label="美美咖报单" :value="0"></el-option>
                <el-option label="传统报单" :value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="医院名称">
              <template>
                <el-select v-model="form.hospitalId" clearable filterable placeholder="请选择">
                  <el-option
                    v-for="item in hospitalOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </template>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="创建时间">
              <el-date-picker
                value-format="yyyy-MM-dd HH:mm:ss"
                v-model="form.dates"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="['00:00:00', '23:59:59']"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- <el-form-item> -->
            <el-button style="margin-left:60px" type="primary" @click="searchFn">查询</el-button>
            <el-button
              plain
              type="primary"
              v-if="permissionJson.indexOf('AdminRepaymentProvider.exportRepaymentAdmin') !=-1"
              class="el-icon-download"
              @click="excelEvent"
            >导出</el-button>
            <!--   v-if="permissionJson.indexOf('AdminRepaymentProvider.batchVerify') !=-1" -->
            <el-button
              style="margin-left:60px"
              type="primary"
              @click="hexiao"
              v-if="permissionJson.indexOf('AdminRepaymentProvider.batchVerify') !=-1"
            >批量核销</el-button>
            <!-- </el-form-item> -->
          </el-col>
        </el-row>
      </el-form>
    </div>
    <!-- 主页列表 -->
    <div class="listDiv" v-loading="loadings">
      <!-- table列表 -->
      <el-table
        :data="tableData"
        class="tableData"
        style="width: 100%"
        ref="multipleTable"
        tooltip-effect="dark"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column type="index" label="序号" width="80"></el-table-column>
        <el-table-column prop="hospitalName" label="医院名称"></el-table-column>
        <el-table-column prop="formType" label="报单类型"></el-table-column>
        <el-table-column prop="repaymentSn" label="回款比率" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.paidRatio">{{ scope.row.paidRatio}} %</span>
          </template>
        </el-table-column>
        <el-table-column prop="repaymentSn" label="回款单号"></el-table-column>
        <el-table-column prop="orderSn" label="流水单号"></el-table-column>
        <el-table-column prop="userName" label="客户姓名"></el-table-column>
        <el-table-column prop="userPhone" label="客户手机号">
          <template slot-scope="scope">
            <span>{{scope.row.userPhone | phonereg}}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="paymentId" label="付款方式">
          <template slot-scope="scope">
            <span>{{ scope.row.paymentId | paytype}}</span>
          </template>
        </el-table-column>-->
        <el-table-column prop="createdAt" label="创建时间"></el-table-column>
        <el-table-column prop="receivableAmount" label="应回款金额"></el-table-column>
        <el-table-column prop="receivedAmount" label="已回款金额"></el-table-column>
        <el-table-column prop="aprovalAmount" label="审批中金额"></el-table-column>
        <el-table-column prop="verifyAmount" label="核销金额"></el-table-column>
        <el-table-column prop="surplusReceivableAmount" label="剩余回款金额"></el-table-column>
        <el-table-column prop="status" label="回款状态">
          <template slot-scope="scope">
            <span>{{ scope.row.status | RS }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="paymentId" label="付款方式"></el-table-column>
        <el-table-column prop="verifyDesc" label="核销备注"></el-table-column>
        <el-table-column prop="isExceed" label="是否逾期">
          <template slot-scope="scope">
            <span v-if="scope.row.isExceed ==0">未逾期</span>
            <span v-if="scope.row.isExceed ==1">已逾期</span>
            <span v-if="scope.row.isExceed ==2">暂无</span>
          </template>
        </el-table-column>
        <el-table-column prop="exceedDays" label="逾期天数">
          <template slot-scope="scope">
            <span
              v-if="scope.row.isExceed ==1"
            >{{ scope.row.isExceed === '0' ? '': scope.row.exceedDays+'天' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="isGrace" label="是否宽限回款">
          <template slot-scope="scope">
            <span>{{ scope.row.isGrace == '0' ? '否':'是' }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" align="center" label="操作" width="150">
          <span slot-scope="scope">
            <el-button
              v-if="permissionJson.indexOf('AdminRepaymentProvider.getRepaymentDetail') !=-1"
              type="text"
              @click="toRoutes('msg',scope.row)"
              size="small"
            >详情</el-button>
            <span v-if="permissionJson.indexOf('AdminRepaymentProvider.updateRepayment') !=-1">
              <el-button
                v-if="scope.row.isGrace == 0 && scope.row.receivableAmount>=0 && (scope.row.status==2||scope.row.status==3)"
                type="text"
                @click="delay(scope.row)"
                size="small"
              >宽限回款</el-button>
            </span>
            <span v-if="permissionJson.indexOf('AdminRepaymentProvider.approvalRepayment') !=-1">
              <el-button
                v-if="(scope.row.status == '2' || scope.row.status == '3' )&& Number(scope.row.surplusReceivableAmount) > 0 "
                type="text"
                @click="verification(scope.row)"
                size="small"
              >核销</el-button>
            </span>
          </span>
        </el-table-column>
      </el-table>
      <!-- 核销弹窗1.0 -->
      <el-dialog
        title="核销单据"
        :visible.sync="dialogVisible"
        :before-close="handleClose"
        width="468px"
      >
        <!-- 输入框 -->
        <el-form
          :inline="true"
          label-width="130px"
          :rules="rules"
          ref="hxForm"
          :model="hxForm"
          label-position="right"
        >
          <el-form-item label="回款单号">
            <span class="spanToInput">{{hxList.repaymentSn}}</span>
          </el-form-item>
          <br />
          <el-form-item label="应回款金额">
            <span class="spanToInput">{{hxList.receivableAmount}}</span>
          </el-form-item>
          <br />
          <el-form-item label="剩余回款金额">
            <span class="spanToInput">{{hxList.surplusReceivableAmount}}</span>
          </el-form-item>
          <br />
          <el-form-item label="核销金额" prop="verifyAmount">
            <el-input
              @blur="hxMoneyChange(hxList.surplusReceivableAmount,hxForm.verifyAmount)"
              v-model="hxForm.verifyAmount"
            ></el-input>
          </el-form-item>
          <br />
          <el-form-item label="核销备注">
            <el-input v-model="hxForm.verifyDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose()">取 消</el-button>
          <el-button
            type="primary"
            @click="hxSubmit('hxForm',hxList.surplusReceivableAmount,hxForm.verifyAmount)"
          >确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分页 -->
      <div class="pagesCon">
        <div>
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="form.pageNum"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="form.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="page_totals"
          ></el-pagination>
        </div>
      </div>
      <!-- 核销弹窗1.5.1 -->
      <el-dialog :title="htitle" :visible.sync="hexiaoVisible" width="468px">
        <p style="display: flex;align-items: center;">
          <span style="width:50px;">备注</span>
          <el-input placeholder="核销备注" v-model="params.verifyDesc"></el-input>
        </p>
        <span slot="footer" class="dialog-footer">
          <el-button @click="hexiaoVisible=false">取 消</el-button>
          <el-button type="primary" @click="sure">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

 <script>
import {
  backList,
  hospitalList,
  updateRepayment,
  expotfun,
  approvalRepayment,
  batchVerify
} from "@/api/financialBack";
import { exportfile } from "@/api/exporfile";
export default {
  name: "financialBackList",
  data() {
    return {
      hxList: {},
      params: {},
      hexiaoVisible: false,
      htitle:
        "注：批量核销后已勾选回款单剩余回款金额将更新为0，是否确定批量核销数据*条？",
      hxForm: {
        verifyAmount: null,
        verifyDesc: null
      },
      dialogVisible: false,
      loadings: true,
      officeOption: [],
      permissionJson: JSON.parse(localStorage.getItem("permissionJson")),
      rules: {
        verifyAmount: [
          {
            required: true,
            message: "请输入核销金额",
            trigger: "blur"
          }
        ]
      },
      backStatus: [
        {
          value: "",
          label: "全部"
        },
        {
          value: "1",
          label: "已回款"
        },
        {
          value: "2",
          label: "未回款"
        },
        {
          value: "3",
          label: "部分回款"
        },
        {
          value: "4",
          label: "未抵扣"
        },
        {
          value: "5",
          label: "已抵扣"
        },
        {
          value: "6",
          label: "抵扣中"
        },
        {
          value: "7",
          label: "已付款"
        }
      ],
      StatusOption: [
        {
          value: "",
          label: "全部"
        },
        {
          value: "0",
          label: "未逾期"
        },
        {
          value: "1",
          label: "已逾期"
        }
      ],
      hospitalOptions: [],
      form: {
        repaymentSn: "",
        orderSn: "",
        status: "",
        userPhone: "",
        username: "",
        hospitalId: "",
        isExceed: "",
        beginCreateDate: null,
        endCreateDate: null,
        dates: [],
        consult: "",
        pageNum: 1,
        pageSize: 10
      },
      tableData: [],
      multipleSelection: [],
      page_sizes: [10, 30, 50, 100],
      page_totals: 60,
      listForm: {
        pageNum: 1,
        pageSize: 10
      }
    };
  },
  watch: {
    "form.dates": function(val) {
      // if(val==null){
      //   this.form.beginCreateDate = null
      //   this.form.endCreateDate = null
      // }
    }
  },
  filters: {
    cardType: function(e) {
      return window.helper.cardType(e);
    },
    RS: function(e) {
      switch (e) {
        case "1":
          return "已回款";
        case "2":
          return "未回款";
        case "3":
          return "部分回款";
        case "4":
          return "未抵扣";
        case "5":
          return "已抵扣";
        case "6":
          return "抵扣中";
        case "7":
          return "已付款";
        default:
          return "暂无";
      }
    },
    paytype: function(val) {
      switch (val) {
        case "0":
          return "旧数据默认值";
        case "1":
          return "自费";
        case "2":
          return "分期";

        default:
          return "暂无";
      }
    }
  },
  created() {
    this.getHospital();
  },
  mounted() {
    this.getList(this.form);
  },
  inject: ["reload"],
  methods: {
    async sure() {
      this.hexiaoVisible = false;
      console.log(this.params);
      let res = await batchVerify(this.params);
      this.$message.warning(res.data.msg);
      if (res.data.code == 0) {
        this.getList(this.form);
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //批量核销
    hexiao() {
      console.log(this.multipleSelection);
      if (!this.multipleSelection.length) {
        this.$message.warning("请勾选处理的选项");
        return;
      }
      let arr = [];
      this.multipleSelection.map(res => {
        arr.push(res.repaymentId);
      });

      this.params.repaymentIds = arr.join(",");
      this.htitle =
        `注：批量核销后已勾选回款单剩余回款金额将更新为0，是否确定批量核销数据` +
        this.multipleSelection.length +
        `条？`;
      this.hexiaoVisible = true;
    },
    //按钮权限
    hasPermission(e) {
      return window.helper.hasPermission(e);
    },
    //成功状态弹窗
    succStatus(txt) {
      this.$message({
        message: txt + "成功",
        type: "success"
      });
    },
    //失败状态弹窗
    errorStatus(txt) {
      this.$message.error(txt + "失败");
    },
    //导出
    excelEvent() {
      let data = {
        ...this.form
      };
      data.pageSize = null;
      data.pageNum = null;
      console.log(data);
      expotfun(data).then(res => {
        exportfile(res, "回款单列表");
      });
    },
    //查询
    searchFn() {
      this.form.pageNum = 1;
      if (this.form.dates) {
        this.form.beginCreateDate = this.form.dates[0];
        this.form.endCreateDate = this.form.dates[1];
      } else {
        this.form.beginCreateDate = null;
        this.form.endCreateDate = null;
      }
      this.getList(this.form);
    },
    // 路由跳转
    toRoutes(e, row) {
      let route = {
        name: e,
        query: { userId: row.repaymentId, orderSn: row.orderSn }
      };
      this.$router.push(route);
    },
    //医院名称
    getHospital() {
      hospitalList().then(res => {
        // console.log(res.data.data)
        if (res.data.data) {
          this.hospitalOptions = res.data.data.map(item => {
            return { value: String(item.id), label: item.name };
          });
        }
      });
    },
    //删除宽限回款单
    delay(val) {
      console.log(val);
      this.$prompt("是否确定将此回款单加入宽限回款列表？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPlaceholder: "备注"
      })
        .then(({ value }) => {
          updateRepayment({
            repaymentId: val.repaymentId,
            isGrace: "1",
            remark: value,
            isRemove: "0",
            graceStatus: "1"
          }).then(res => {
            // console.log(res)
            if (res.data.code == 0) {
              this.getList(this.form);
              this.$message({
                type: "success",
                message: "成功 "
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消操作"
          });
        });
    },
    //列表数据获取
    getList(e) {
      this.loadings = true;
      let datas = e;
      backList(datas)
        .then(res => {
          if (res.data.code == 0) {
            this.tableData = res.data.data.list;
            this.page_totals = res.data.data.count;
          } else {
            this.$message.error(res.data.msg);
          }
          this.loadings = false;
        })
        .catch(error => {
          this.$message.error(error);
          this.loadings = false;
        });
    },
    // 核销按钮
    verification(e) {
      this.hxList = e;
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.hxForm.resetFields();
      });
    },
    // 核销金额失焦事件
    hxMoneyChange(oldMoney, newMoney) {
      if (
        Number(newMoney) > Number(oldMoney) ||
        Number(newMoney) < 0 ||
        isNaN(newMoney)
      ) {
        this.hxForm.verifyAmount = null;
      } else {
        this.hxForm.verifyAmount = this.hxForm.verifyAmount
          ? parseInt(this.hxForm.verifyAmount)
          : null;
      }
    },
    // 核销取消按钮
    handleClose() {
      this.dialogVisible = false;
    },
    // 核销提交
    hxSubmit(e, oldMoney, newMoney) {
      this.$refs[e].validate(valid => {
        if (valid) {
          let datas = { ...this.hxForm };
          datas["verifyAmount"] = String(datas["verifyAmount"]);
          datas["repaymentId"] = this.hxList.repaymentId;
          datas[
            "surplusReceivableAmount"
          ] = this.hxList.surplusReceivableAmount;
          approvalRepayment(datas)
            .then(res => {
              if (res.data.code == 0) {
                this.succStatus("核销");
                this.reload();
              } else {
                this.$message.error(res.data.msg);
              }
              this.loadings = false;
            })
            .catch(error => {
              this.$message.error(error);
              this.loadings = false;
            });
          this.dialogVisible = false;
        } else {
          this.$message({
            message: "必填项不能为空",
            type: "warning"
          });
        }
      });
    },
    //成功状态弹窗
    succStatus(txt) {
      this.$message({
        message: txt + "成功",
        type: "success"
      });
    },
    //改变页面条数
    handleSizeChange(val) {
      this.form.pageSize = val;
      this.getList(this.form);
    },
    //选择页数
    handleCurrentChange(val) {
      this.form.pageNum = val;
      this.getList(this.form);
    }
  }
};
</script>

<style scoped>
/* 分页 */
.pagesCon {
  height: 40px;
  margin-top: 20px;
}
.pagesCon > div {
  float: right;
}
.el-table {
  width: 99.9% !important;
}
/* 表单样式修改 */
.el-range-editor--medium.el-input__inner {
  width: 236px;
}
</style>